<template>
  <div class="outmain ba_f">
    <div class="shuju_title mar_b20">
      <div class="shuju_title_text">
        <span>商品列表</span>
      </div>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="已上架" name="1">
        <span slot="label">已上架({{ allTotal == "" ? 0 : allTotal }})</span>
      </el-tab-pane>
      <el-tab-pane label="库存不足" name="2">
        <span slot="label">库存不足({{ noStock == "" ? 0 : noStock }})</span>
      </el-tab-pane>
      <el-tab-pane label="已售罄" name="5">
        <span slot="label">已售罄({{ sellOutTotal == "" ? 0 : sellOutTotal }})</span>
      </el-tab-pane>
      <el-tab-pane label="已下架" name="3">
        <span slot="label">已下架({{ errDisplay == "" ? 0 : errDisplay }})</span>
      </el-tab-pane>
      <el-tab-pane label="待上架" name="4">
        <span slot="label">待上架({{ noDisplay == "" ? 0 : noDisplay }})</span>
      </el-tab-pane>
      <el-tab-pane label="回收站" name="6">
        <span slot="label">回收站({{ recycleTotal == "" ? 0 : recycleTotal }})</span>
      </el-tab-pane>
    </el-tabs>
    <div class="content ba_f">
      <div class="flex-bet pad_20">
        <div>
          <el-form :inline="true" :model="formInline" class="demo-form-inline searchform">
            <div>
              <el-form-item label="商品名称">
                <el-input v-model="formInline.name" size="medium" placeholder="请输入商品名称"
                          @input="onSearch"></el-input>
              </el-form-item>
              <el-form-item label="商品分类">
                <el-select v-model="formInline.typePid" clearable placeholder="请选择分类" @change="onSearch">
                  <el-option v-for="item in typeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="medium" @click="onSearch">搜索</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="flex">
          <ul class="flex tablebtn mar_r40" v-show="activeName!='6'">
            <li class="t_btn bor_dd curs">
              <el-button size="medium" @click="handleGoodEdit('row','1')">沽清</el-button>
            </li>
            <li class="t_btn bor_dd curs">
              <el-button size="medium" @click="handleGoodEdit('row','2')">置满</el-button>
            </li>
            <li class="t_btn bor_dd curs">
              <el-button size="medium" @click="handlexgkc()">修改库存</el-button>
            </li>
            <li class="t_btn bor_dd curs">
              <el-button size="medium" @click="goodDown('row',2)">上架</el-button>
            </li>
            <li class="t_btn bor_dd curs">
              <el-button size="medium" @click="goodDown('row',1)">下架</el-button>
            </li>
            <!--                        <li class="t_btn bor_dd curs">-->
            <!--                            <el-button size="medium">-->
            <!--                                <el-dropdown>-->
            <!--                                      <span class="">-->
            <!--                                      更多<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
            <!--                                      </span>-->
            <!--                                    <el-dropdown-menu slot="dropdown">-->
            <!--                                        <el-dropdown-item>修改包装费</el-dropdown-item>-->
            <!--                                        &lt;!&ndash;                                                            <el-dropdown-item>移动分类</el-dropdown-item>&ndash;&gt;-->
            <!--                                        &lt;!&ndash;                                                            <el-dropdown-item>修改售卖时间</el-dropdown-item>&ndash;&gt;-->
            <!--                                    </el-dropdown-menu>-->
            <!--                                </el-dropdown>-->
            <!--                            </el-button>-->
            <!--                        </li>-->
          </ul>
          <div>
            <el-button size="medium" @click="handleDelete">批量删除</el-button>
            <el-button type="primary" size="medium" class="mar_l10" @click="addgood()">添加商品</el-button>
          </div>
        </div>
      </div>
      <div class="mar_b20">
        <el-button size="medium" @click="handletb" type="success">同步商品到门店</el-button>
        <el-button size="medium" @click="handletbwm" type="danger">同步商品到店内</el-button>
        <el-checkbox v-model="allGood" class="mar_l10" @change="toggleSelection(list)">全部商品</el-checkbox>
        <div class="yb_margin lh16">如需同步所有商品到门店请勾选此选项，如需同步局部商品到门店请勿勾选！</div>
      </div>
      <div class="tabledata">
        <el-table ref="multipleTable" v-loading="listLoading" :element-loading-text="elementLoadingText" :data="list"
                  stripe style="width: 100%" @selection-change="setSelectRows">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="sort" label="排序" width="100">
            <template slot-scope="scope">
              <div class="flex bixuan">
                <div class>{{ scope.row.sort }}</div>
                <span class="el-icon-edit-outline curs subjectcolor2 mar_l5"
                      @click="handleEdit(scope.row,'sort')"></span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="商品ID" width="100"></el-table-column>
          <el-table-column prop="name" label="商品名称" width="390">
            <template slot-scope="scope">
              <div class="flex flex-y-top">
                <div class>
                  <img class="goodlogo bor_rad5" :src="scope.row.icon"/>
                </div>
                <div class="mar_l10">
                  <div class="flex bixuan">
                    <div class>{{ scope.row.name }}</div>
                    <span class="el-icon-edit-outline curs subjectcolor2" @click="handleEdit(scope.row,'name')"></span>
                    <el-tag size="medium" type="danger" class="mar_l10" v-show="scope.row.isRecommend=='1'">推荐
                    </el-tag>
                    <el-tag size="medium" style="background: #faf3ec;" type="danger" class="mar_l10"
                            v-show="scope.row.discountOpen=='1'">
                      <span style="color: #ca8743;">会员价</span>
                    </el-tag>
                  </div>
                  <p class="fon_12 color_9 mar_t5">销量：{{ scope.row.salesNum }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="category_name" label="商品分类">
            <template slot-scope="scope">
              <div class="flex">
                <p>
                  <el-tag size="medium" type="info">{{ scope.row.category_name }}</el-tag>
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格/成本">
            <template slot-scope="scope">
              <div v-if="scope.row.isSpecs=='2'">
                <!--                todo 将数字表达抽取-->
                ￥{{ scope.row.price }}/￥{{ (scope.row.price * 0.6).toFixed(2) }}
                <el-button type="text" class="el-icon-edit-outline" @click="handleEdit(scope.row,'price')"
                           v-show="activeName!='6'"></el-button>
              </div>
              <div v-else>
                {{ scope.row.price }}~{{ scope.row.maxPrice }}/{{
                  (scope.row.price * 0.6).toFixed(2)
                }}~{{ (scope.row.maxPrice * 0.6).toFixed(2) }}
                <el-button type="text" class="el-icon-edit-outline" @click="handleGoodSpec(scope.row,'dPrice')"
                           v-show="activeName!='6'"></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存">
            <template slot-scope="scope">
              <div class="flex" v-if="scope.row.isSpecs=='2'">
                <div class="mar_r5">{{ scope.row.stock }}</div>
                <span v-show="activeName!='6'">
                  <el-button type="text" class="el-icon-edit-outline"
                             @click="handleEdit(scope.row,'stock')"></el-button>
                  <el-button type="text" class="color_6" @click="handleGoodEdit(scope.row,'1')">估清</el-button>
                  <el-button type="text" class="color_6" @click="handleGoodEdit(scope.row,'2')">置满</el-button>
                </span>
              </div>
              <div v-else>
                多规格
                <el-button type="text" class="color_6 mar_l10" @click="handleGoodSpec(scope.row,'dStock')"
                           v-show="activeName!='6'">库存管理
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <div class="flex gengduo" v-show="activeName!='6'">
                <div class="ruleHot" v-show="scope.row.display=='1'"></div>
                <el-button type="text" @click="goodDown(scope.row,1)" v-show="scope.row.display=='1'">下架</el-button>
                <div class="redHot" v-show="scope.row.display=='2'"></div>
                <el-button type="text" @click="goodDown(scope.row,2)" v-show="scope.row.display=='2'">上架</el-button>
                <el-button type="text" @click="editGood(scope.row)">编辑</el-button>
                <el-button type="text" @click="showCostCard(scope.row)">成本卡</el-button>
<!--                <el-button type="text" @click="vipGood(scope.row)">会员价</el-button>-->
                <el-dropdown trigger="click">
                  <span class="curs subjectcolor2 mar_l10">
                    更多
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <!--                                        <el-dropdown-item>-->
                    <!--                                            <a class="alinks">商品链接</a>-->
                    <!--                                        </el-dropdown-item>-->
                    <el-dropdown-item>
                      <a @click="tongjiGood(scope.row)" class="alinks">商品统计</a>
                    </el-dropdown-item>
                    <el-dropdown-item v-show="scope.row.isRecommend=='2'">
                      <a @click="handleRecommend(scope.row,2)" class="alinks">商品推荐</a>
                    </el-dropdown-item>
                    <el-dropdown-item v-show="scope.row.isRecommend=='1'">
                      <a @click="handleRecommend(scope.row,1)" class="alinks">取消推荐</a>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <a @click="qbxj(scope.row)" class="alinks">全部下架</a>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <a @click="handleDelete(scope.row)" class="alinks">商品删除</a>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <el-button type="text" @click="goodRecovery(scope.row)" v-show="activeName=='6'">恢复</el-button>
              <el-button type="text" @click="handleDelete(scope.row)" v-show="activeName=='6'">商品删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog title="批量修改库存" :visible.sync="dialogVisible" width="30%">
          <div>
            <el-input v-model.trim="plkc" type="number" autocomplete="off"></el-input>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="qrplxg()">确 定</el-button>
          </span>
        </el-dialog>
        <el-pagination background layout="prev, pager, next" :total="page.total" :page-size="page.pagesize"
                       :current-page.sync="page.currentPage" @current-change="handleCurrentChange"></el-pagination>
        <edit ref="edit" @fetchData="fetchData"></edit>
        <specs ref="specs" @fetchData="fetchData"></specs>
        <EditVip ref="editvip" @fetchData="fetchData"></EditVip>
        <tbGoods ref="tbgoods" @fetchData="fetchData"></tbGoods>
      </div>
    </div>
    <el-dialog
        title="菜品成本卡"
        :visible.sync="costCard"
        width="70%"
        :before-close="handleClose">
      <div>
        <el-table :data="tableData" style="width: 100%" >
          <el-table-column prop="material" label="原料品名"></el-table-column>
          <el-table-column prop="net_quantity" label="净用量" :formatter="formatNumber"></el-table-column>
          <el-table-column prop="unit" label="单位"></el-table-column>
          <el-table-column prop="unit_price" label="单价" :formatter="formatNumber"></el-table-column>
          <el-table-column prop="total_cost" label="合计" :formatter="formatNumber"></el-table-column>
          <div slot="append" style="display:flex;">
              <div  style="text-align: left; width: 50%;">
                合计
              </div>
              <div style="text-align: right; width: 50%;">
                {{ tableData.reduce((total, item) => total + item.total_cost, 0).toFixed(2) }}
              </div>

          </div>

        </el-table>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import Edit from './components/goodlistedit';
import EditVip from './components/goodlistvip';
import Specs from './components/specs';
import tbGoods from './components/tbgoods';
import {getGoodList, goodDel, setGoodNum, goodDown, goodsRecovery, allDown, mergeGoods} from '@/api/good';

export default {
  name: 'goodlist',
  components: {Edit, Specs, EditVip, tbGoods},
  created() {
    if (this.$route.query.currentPage || this.$route.query.activeName) {
      this.page.currentPage = +this.$route.query.currentPage
      this.activeName = this.$route.query.activeName ? this.$route.query.activeName : '1'
      this.type = this.$route.query.type ? this.$route.query.type : 1
      this.fetchData();
    } else {
      this.fetchData();
    }
  },
  data() {
    return {
      costCard: false, //显示成本卡
      tableData: [
        {
          material: 'Material 1',
          net_quantity: 10.5,
          unit: 'kg',
          unit_price: 2.5,
          total_cost: 26.25,
        },
        {
          material: 'Material 2',
          net_quantity: 7.25,
          unit: 'lb',
          unit_price: 3.75,
          total_cost: 27.19,
        },
        {
          material: 'Material 3',
          net_quantity: 15.75,
          unit: 'kg',
          unit_price: 1.5,
          total_cost: 23.63,
        },
      ],
      formInline: {
        name: '',
        typePid: ''
      },
      typeOptions: [],
      activeName: '1',
      tdHover: false, //鼠标移动显示编辑图标
      list: [],
      listLoading: true,
      selectRows: '',
      elementLoadingText: '正在加载...',
      page: {
        total: 0,
        size: 10,
        currentPage: 1
      },
      stock: '1',
      msg: '',
      display: '1',
      dialogVisible: false,
      plkc: '',

      allTotal: '',
      errDisplay: '',
      noDisplay: '',
      noStock: '',
      sellOutTotal: '',
      type: 1,
      recycleTotal: '',
      allGood: false,
    };
  },
  methods: {
    formatNumber(row, column, cellValue) {
      return parseFloat(cellValue).toFixed(2);
    },
    async fetchData() {
      var params = {
        page: this.page.currentPage,
        type: this.type,
        name: this.formInline.name,
        typePid: this.formInline.typePid
      };
      this.listLoading = false;
      const {data, count, msg} = await getGoodList(params);
      this.msg = msg;
      this.list = data.data;
      this.page.total = count;
      this.typeOptions = data.categoryData ? data.categoryData : [];
      this.allTotal = data.allTotal ? data.allTotal : 0;
      this.errDisplay = data.errDisplay ? data.errDisplay : 0;
      this.noDisplay = data.noDisplay ? data.noDisplay : 0;
      this.noStock = data.noStock ? data.noStock : 0;
      this.sellOutTotal = data.sellOutTotal ? data.sellOutTotal : 0;
      this.recycleTotal = data.recycleTotal ? data.recycleTotal : 0;
    },
    onSearch() {
      this.fetchData();
    },
    setSelectRows(val) {
      this.selectRows = val;
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.fetchData();
    },

    addgood() {
      if (this.msg == '无效的门店') {
        this.$baseConfirm2('请完善门店信息', null, '去完善信息', null, async () => {
          this.$router.push({path: '/storeinformation'});
        });
      } else if (this.msg == '请添加商品分类') {
        this.$baseConfirm2('请先添加商品分类', null, '去添加分类', null, async () => {
          this.$router.push({path: '/goodclassify'});
        });
      } else if (this.msg == '请添加商品单位') {
        this.$baseConfirm2('请先添加商品单位', null, '去添加单位', null, async () => {
          this.$router.push({path: '/goodunit'});
        });
      } else {
        this.$router.push(`/addgood1?currentPage=${this.page.currentPage}&activeName=${this.activeName}&type=${this.type}`);
      }
    },
    editGood(row) {
      this.$router.push(`/addgood1?id=${row.id}&currentPage=${this.page.currentPage}&activeName=${this.activeName}&type=${this.type}`);
    },
    showCostCard(row) {
      if (row.id)
        this.costCard = true;
    },
    vipGood(row) {
      if (row.id) {
        this.$refs['editvip'].showEdit(row);
      }
    },
    handleGoodSpec(row, type) {
      if (row.id) {
        this.$refs['specs'].showEdit(row, type);
      }
    },
    handleEdit(row, type) {
      if (row.id) {
        this.$refs['edit'].showEdit(row, type);
      }
    },
    async handleTabClick() {
      // console.log(this.activeName);
      this.page.currentPage = 1;
      switch (+this.activeName) {
        case 1:
          this.stock = 1;
          this.display = 1;
          this.type = 1;
          this.fetchData();
          break;
        case 2:
          this.stock = 0;
          this.display = 1;
          this.type = 2;
          this.fetchData();
          break;
        case 3:
          this.display = 2;
          this.stock = 1;
          this.type = 4;
          this.fetchData();
          break;
        case 4:
          this.display = 3;
          this.stock = 1;
          this.type = 5;
          this.fetchData();
          break;
        case 5:
          this.display = 1;
          this.stock = 0;
          this.type = 3;
          this.fetchData();
          break;
        case 6:
          this.display = 1;
          this.stock = 0;
          this.type = 6;
          this.fetchData();
          break;
      }
    },
    handleDelete(row) {
      if (row.id) {
        let type = 1;
        if (this.activeName == '6') {
          type = 2;
        }
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const {msg} = await goodDel({id: row.id, type: type});
          this.$baseMessage(msg, 'success');
          this.fetchData();
        });
      } else {
        if (this.selectRows.length > 0 || this.allGood) {
          var tsy2 = ''
          if (this.allGood) {
            tsy2 = '你确定要删除所有商品吗'
          } else {
            tsy2 = '你确定要删除选中项吗'
          }
          const id = this.selectRows.map((item) => item.id);
          this.$baseConfirm(tsy2, null, async () => {
            const {msg} = await goodDel({id: this.allGood ? 'all' : id, type: this.activeName == '6' ? 2 : 1});
            this.$baseMessage(msg, 'success');
            this.fetchData();
          });
        } else {
          this.$baseMessage('未选中任何行', 'error');
          return false;
        }
      }
    },
    handletb() {
      if (this.selectRows.length > 0 || this.allGood) {
        const goodIds = this.selectRows.map((item) => item.id);
        this.$refs['tbgoods'].showEdit(goodIds, this.allGood);
        // this.$baseConfirm('你确定要删除选中项吗', null, async () => {
        //   const { msg } = await changeGoods({ goodIds,});
        //   this.$baseMessage(msg, 'success');
        //   this.fetchData();
        // });
      } else {
        this.$baseMessage('未选中任何商品', 'error');
        return false;
      }
    },
    handletbwm() {
      if (this.selectRows.length > 0 || this.allGood) {
        const goodIds = this.selectRows.map((item) => item.id);
        this.$baseConfirm('您确定要将外卖商品以及商品分类同步到店内吗？（注意：此操作会损耗大量的服务器资源，请谨慎操作！）', null, async () => {
          this.listLoading2 = true;
          const {msg} = await mergeGoods({goodIds: this.allGood ? 'all' : goodIds,});
          this.listLoading2 = false;
          this.$baseMessage(msg, 'success');
          this.fetchData();
        });
      } else {
        this.$baseMessage('未选中任何商品', 'error');
        return false;
      }
    },
    toggleSelection(row) {
      if (!this.selectRows.length) {
        row.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        })
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    async goodRecovery(row) {
      const {msg} = await goodsRecovery({id: row.id});
      this.$baseMessage(msg, 'success');
      this.fetchData();
    },
    handlexgkc() {
      if (this.selectRows.length > 0) {
        this.dialogVisible = true;
      } else {
        this.$baseMessage('未选中任何行', 'error');
        return false;
      }
    },
    async qrplxg() {
      const id = this.selectRows.map((item) => item.id);
      if (this.plkc) {
        const {msg} = await setGoodNum({id, num: this.plkc});
        this.$baseMessage(msg, 'success');
        this.dialogVisible = false;
        this.fetchData();
      } else {
        this.$baseMessage('未输入内容', 'error');
        return false;
      }
    },
    goodDown(row, type) {
      var text;
      if (type == '1') {
        text = '下架';
      } else {
        text = '上架';
      }
      if (row.id) {
        this.$baseConfirm(`你确定要${text}当前商品吗`, null, async () => {
          const {msg} = await goodDown({id: row.id, display: type});
          this.$baseMessage(msg, 'success');
          this.fetchData();
        });
      } else {
        if (this.selectRows.length > 0) {
          const id = this.selectRows.map((item) => item.id);
          this.$baseConfirm(`你确定${text}商品吗`, null, async () => {
            const {msg} = await goodDown({id, display: type});
            this.$baseMessage(msg, 'success');
            this.fetchData();
          });
        } else {
          this.$baseMessage('未选中任何行', 'error');
          return false;
        }
      }
    },
    handleGoodEdit(row, type) {
      var text;
      if (type == '1') {
        text = '估清';
      } else {
        text = '置满';
      }
      if (row.id) {
        this.$baseConfirm(`你确定${text}商品吗`, null, async () => {
          const {msg} = await setGoodNum({id: row.id, type});
          this.$baseMessage(msg, 'success');
          this.fetchData();
        });
      } else {
        if (this.selectRows.length > 0) {
          const id = this.selectRows.map((item) => item.id);
          this.$baseConfirm(`你确定${text}商品吗`, null, async () => {
            const {msg} = await setGoodNum({id, type});
            this.$baseMessage(msg, 'success');
            this.fetchData();
          });
        } else {
          this.$baseMessage('未选中任何行', 'error');
          return false;
        }
      }
    },
    handleRecommend(row, type) {
      var text;
      if (type == '1') {
        text = '取消推荐';
      } else {
        text = '推荐';
      }
      if (row.id) {
        this.$baseConfirm(`你确定要${text}当前商品吗`, null, async () => {
          const {msg} = await goodDown({id: row.id, isRecommend: row.isRecommend});
          this.$baseMessage(msg, 'success');
          this.fetchData();
        });
      }
    },
    tongjiGood(row) {
      this.$router.push(`/goodtongji?id=${row.id}`);
    },
    qbxj(row) {
      if (row.id) {
        this.$baseConfirm(`你确定要全部下架该商品吗`, null, async () => {
          const {msg} = await allDown({id: row.id,});
          this.$baseMessage(msg, 'success');
          this.fetchData();
        });
      }
    },
  }
};
</script>
<style lang="scss">
.goodlogo {
  width: 50px;
  height: 50px;
}

.bgbox {
  padding: 4px 12px;
}

.ivu-page {
  margin-top: 20px;
}

.alinks {
  color: #606266;
}

.alinks:hover {
  color: #2d8cf0;
}

.redHot {
  width: 6px;
  height: 6px;
  background: #f85959;
  border-radius: 50%;
  margin-left: 10px;
  margin-right: 5px;
}

.ruleHot {
  width: 6px;
  height: 6px;
  background: #17c295;
  border-radius: 50%;
  margin-left: 10px;
  margin-right: 5px;
}

.bixuan .el-tag--medium {
  height: 20px;
  line-height: 18px;
}

.bixuan .el-tag {
  border-radius: 128px;
}

/*.tablebtn .el-button{*/
/*   border: none !important;*/
/*}*/
/*.tablebtn .el-button:hover {*/
/*    !*color: #409EFF;*!*/
/*    !*border-color: #c6e2ff;*!*/
/*    background-color: #fff;*/
/*}*/
/*.ivu-modal-mask {*/
/*    background-color: rgba(55,55,55,.3) !important;*/
/*}*/
</style>
